package com.zoroki.hmusic.util;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.Cache;
import org.springframework.cache.concurrent.ConcurrentMapCache;
import org.springframework.cache.concurrent.ConcurrentMapCacheManager;

import java.io.Serializable;
import java.util.Objects;

@Slf4j
public class VerificationCodeUtil {
    private static final String VerificationCodes = "ABCDEFGHJKMNOPQRSTUVWXYZabcdefghjkmnopqrstuvwxyz1234567890";


    public static final ConcurrentMapCache cache;

    static {
        cache = new ConcurrentMapCache("Code");
    }


    public static String getCode(int length) {
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < length; i++) {
            char c = VerificationCodes.charAt((int) (Math.random() * VerificationCodes.length()));
            sb.append(c);
        }
        return sb.toString();
    }

    public static void setCode(String key, String value) {
        log.info(key + " : " + value);
        cache.put(key, value);

    }

    public static boolean checkCode(String email, String code) {
        String saveCode = Objects.requireNonNull(Objects.requireNonNull(cache.get("code" + email)).get()).toString();
        log.info("code == saveCode => " + code + " == " + saveCode);
        if (saveCode != null) {
            return code.equals(saveCode);
        }
        return false;
    }

}
